Chapter 9: Other C.R.U.D. Operations

So far, we have implemented list and create todo API endpoints. A very common occurring pattern is retrieving,

editing and deleting a specific model instance. To achieve this, we implement a get(), put() and delete() endpoint.

Django REST Framework provides the built-in RetrieveUpdateDestroyAPIView to automatically implement the

get(), put() and delete() endpoint.

Let’s first create an API path for it by adding in todobackend/api/urls.py:

Modify Bold Code

...

urlpatterns = [

path('todos/', views.TodoListCreate.as_view()),

path('todos/<int:pk>', views.TodoRetrieveUpdateDestroy.as_view()),

]

That is, to retrieve, update or delete an individual todo, the endpoint will be something like:

localhost:8000/api/todos/123 (‘123’ being the todo’s id)

TodoRetrieveUpdateDestroy

Next in todobackend/api/views.py, we create the TodoRetrieveUpdateDestroy generic view by adding:

Modify Bold Code

...

class TodoListCreate(generics.ListCreateAPIView):

...

class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):

serializer_class = TodoSerializer

permission_classes = [permissions.IsAuthenticated]

def get_queryset(self):

user = self.request.user

# user can only update, delete own posts

return Todo.objects.filter(user=user)

Like the ListCreateAPIView, RetrieveUpdateDestroyAPIView requires two mandatory attributes which are

serializer_class and queryset.

Queryset here automatically retrieves just the todo instance for the id specified in the endpoint e.g.

localhost:8000/api/todos/123

Testing our App

In your browser, navigate to http://localhost:8000/api/todos/<todo_id> e.g. http://localhost:8000/api/todos/1, you

will be able to execute a DELETE request by clicking on the ‘DELETE’ button (fig. 1).

Figure 1

In the same endpoint via the browser, you will be able to execute a PUT request through a form to update a todo

(fig. 2).